<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 方法一
      var str1 = " 123 ";
      //   console.log(str1.length); //5
      var newStr1 = str1.trim();
      //   console.log(newStr1.length); //3
      // -----------------------------------------------------------------------------
      //方法二
      var str2 = "   666   ";
      console.log(str2.length); //9

      var start = 0;
      var end = str2.length - 1;

      // 循环找到第一个非空格字符的位置
      //   有几个空格就会加几次
      while (start <= end && str2[start] === " ") {
        start++;
      }
      console.log(start); //3

      // 循环找到最后一个非空格字符的位置
      while (end >= start && str2[end] === " ") {
        end--;
      }
      console.log(end); //5

      // 返回去除首尾空格后的字符串
      var newStr2 = str2.slice(start, end + 1);
      console.log(newStr2);
      console.log(newStr2.length); //3
    </script>
  </body>
</html>
